package top.ruanlitao.shortlink.project.config;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ip2region 配置
 */
@Slf4j
@Configuration
public class Ip2RegionConfig {

    @Value("${short-link.ip2region.db-path}")
    public String IP2REGION_DB_PATH;

    @Bean(destroyMethod = "close", name = "ip2reginSearcher")
    public Searcher searcher() {
        // 1、从 dbPath 加载整个 xdb 到内存。
        byte[] cBuff;
        try {
            cBuff = Searcher.loadContentFromFile(IP2REGION_DB_PATH);
        } catch (Exception e) {
            log.error("failed to load content from {} \n", IP2REGION_DB_PATH, e);
            return null;
        }

        // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
        Searcher searcher;
        try {
            searcher = Searcher.newWithBuffer(cBuff);
        } catch (Exception e) {
            log.error("failed to create content cached searcher \n", e);
            return null;
        }
        return searcher;
    }
}
